package com.lee.boot.head.first.demo.util;

import com.alibaba.fastjson.JSONObject;
import okhttp3.*;
import org.springframework.util.StringUtils;


import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;




/**
 * @author fcx
 * Created by fcx on 2017/10/11 0011.
 */
public class OkHttpUtils {
    /**
     * 初始化自己
     */
    private static OkHttpUtils OkHttpUtils;

    /**
     * 客户端 builder
     */
    private static OkHttpClient.Builder builder;
    /**
     * 默认客户端
     */
    private static OkHttpClient client;

    /**
     * 链接超时时间
     */
    private static long CONNECT_TIMEOUT = 5;
    /**
     * 读超时时间
     */
    private static long READ_TIME = 10;
    /**
     * 写超时时间
     */
    private static long WRITE_TIMEOUT = 10;

    static {
        //初始化 builder
        if (builder == null) {
            OkHttpClient okHttpClient = new OkHttpClient();
            builder = okHttpClient.newBuilder();
            builder.connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS);
            builder.readTimeout(READ_TIME, TimeUnit.SECONDS);
            builder.writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS);
        }
        if (client == null) {
            client = builder.build();
        }
        if (OkHttpUtils == null) {
            OkHttpUtils = new OkHttpUtils();
        }
    }

    /**
     * 普通 get请求 返回 String
     *
     * @param url
     * @return
     * @throws IOException
     */
    public String get(String url) throws IOException {
        Request request = buildRequest(url, false, null);
        Response response = response = client.newCall(request).execute();
        return response.body().string();
    }

    /**
     * 普通 post 请求 返回 string
     *
     * @param url
     * @param params
     * @return
     * @throws IOException
     */
    public static String post(String url, Map<String, Object> params) throws IOException {

        Request request = buildRequest(url, true, params);
        Response response = client.newCall(request).execute();
        return response.body().string();
    }

    /**
     * 生成请求方法
     *
     * @param url
     * @param methodFlag true post false get
     * @param params
     * @return
     */
    private static Request buildRequest(String url, boolean methodFlag, Map<String, Object> params) {

        Request.Builder builder = new Request.Builder().url(url);

        if (methodFlag) {
            RequestBody body = builderFormData(params);
            builder.post(body);
        } else {
            builder.get();
        }
        return builder.build();
    }

    /**
     * post 方法 生成 请求体 只适用于 String 类型
     *
     * @param params
     * @return
     */
    private static RequestBody builderFormData(Map<String, Object> params) {
        FormBody.Builder builder = new FormBody.Builder();
        if (params != null) {
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                if (!(StringUtils.isEmpty(entry.getKey())) && !StringUtils.isEmpty(entry.getValue().toString())) {
                    builder.add(entry.getKey(), entry.getValue().toString());
                }
            }
        }
        return builder.build();
    }


    /**
     * post json 数据
     *
     * @param url
     * @param json
     * @return
     * @throws IOException
     */
    public static String postJson(String url, String json) throws IOException {
        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        RequestBody body = RequestBody.create(JSON, json);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        Response response = client.newCall(request).execute();
        return response.body().string();
    }

    /**
     * 调用其他模块接口 直接返回code
     *
     * @param url
     * @param params
     * @return 请求返回的code
     * @throws IOException
     */
    public static String postReturnCode(String url, Map<String, Object> params) throws IOException {
        Request request = buildRequest(url, true, params);
        Response response = client.newCall(request).execute();
        String result = response.body().string();
        return getResultFromJson(result, "code");
    }

    private static String getResultFromJson(String result, String code) {
        return "";
    }

    public static void main(String[] args) {
        try {
            Map<String, Object> map = new HashMap<>();
            map.put("photographerCode", "100000010");
            map.put("potographerId", "2");
            map.put("token", "e76bc408f5204dc487e8a4630aca0515");
            System.out.println(post("http://115.29.144.237/dyfs/comment/queryCommentListByPotographerId", map));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void sendFile(byte[] bytes){
        MediaType mediaType = MediaType.parse("text/x-markdown; charset=utf-8");
        OkHttpClient okHttpClient = new OkHttpClient();

        File file = new File("test.md");
        Request request = new Request.Builder()
                .url("https://api.github.com/markdown/raw")
                .post(RequestBody.create(mediaType, file))
                .build();




    }



    /**
     * 请求阿里查询银行卡的类型
     * 返回示例：
     * {
     * "bank": "ABC",
     * "cardType": "DC",
     * "key": "6228430120000000000",
     * "messages": [],
     * "stat": "ok",
     * "validated": true
     * }
     *
     * @param cardNo
     * @return
     * @throws IOException
     */
    public String getCardTypeByAli(String cardNo) throws IOException {
        String url = "https://ccdcapi.alipay.com/validateAndCacheCardInfo.json?_input_charset=utf-8&cardNo=" + cardNo + "&cardBinCheck=true";
        Request.Builder builder = new Request.Builder();
        builder.url(url);
        OkHttpClient client = new OkHttpClient();
        Request build = builder.build();
        Call call = client.newCall(build);
        Response execute = call.execute();
        String string = execute.body().string();
        JSONObject jsonObject = JSONObject.parseObject(string);
        String cardType = (String) jsonObject.get("cardType");
        return cardType;
    }


}
